<?php

namespace App\Third;


use Illuminate\Support\Facades\Cache;
use GuzzleHttp\Client;

class AccessToken {
    private $appid;
    private $secret;

    public function __construct($appid, $secret){
        $this->appid = $appid;
        $this->secret = $secret;
    }

    public function getAccessToken($todo = 0) {
        if(Cache::has('xcx_access_token_'.$this->appid) && $todo === 0) {
            return Cache::get('xcx_access_token_'.$this->appid);
        } else {
            $client = new Client();
            $data = [
                'query' => [
                    'grant_type' => 'client_credential',
                    'appid' => $this->appid,
                    'secret' => $this->secret
                ]
            ];

            // 发送 get 请求
            $response = $client->get(config('xcx.get_access_token_url'), $data);

            $callback_arr = json_decode($response->getBody()->getContents());
//            $callback_arr= $this->sendRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret, "", "", "GET");
            Cache::pull('xcx_access_token_'.$this->appid);
            Cache::add('xcx_access_token_'.$this->appid, $callback_arr->access_token, 116);
            return $callback_arr->access_token;
        }
    }

    public function getGiteeAccessToken($todo = 0) {
        if(Cache::has('gitee_access_token_'.$this->appid) && $todo === 0) {
            info('0000');
            return Cache::get('gitee_access_token_'.$this->appid);
        } else {
            $client = new Client();
            $data = [
                'form_params' => [
                    'grant_type' => 'password',
                    'username' => config('gitee.username'),
                    'password' => config('gitee.password'),
                    'client_id' => $this->appid,
                    'client_secret' => $this->secret,
                    'scope' => config('gitee.scope'),
                ]
            ];
            $response = $client->post(config('gitee.get_access_token_url'), $data);
            $callback_arr = json_decode((string)$response->getBody());
            Cache::pull('gitee_access_token_'.$this->appid);
            Cache::add('gitee_access_token_'.$this->appid, $callback_arr->access_token, 660);
            return $callback_arr->access_token;
        }
    }
}